package org.example;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class Download {

    public static void main(String[] args) {
        int totalPage = 10;
        for (int i = 1; i <= totalPage; i++) {
            String baiduLogoUrl = "https://book.pep.com.cn/1221001602141/files/mobile/" + i + ".jpg?230217151344";
            System.out.println(String.format("正在下载第【%d】张，共【%d】张", i, totalPage));
            downloadPicture(baiduLogoUrl, "D:\\Document\\000000\\Books\\666\\" + i + ".png");
        }
    }

    /**
     * 下载网络图片
     *
     * @param urlList 网络路径
     * @param path    保存路径
     */
    public static void downloadPicture(String urlList, String path) {
        URL url = null;
        try {
            try {
                url = new URL(urlList);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
